<template>
    <div>
        <div>
            <nav-bar class="nav-bar">
                <template v-slot:default>
                    {{title}}
                </template>
            </nav-bar>
        </div>
        <div class="a">
            <van-address-edit
                :area-list="areaList"
                :address-info="addressInfo"
                :show-delete="type == 'edit'"
                show-set-default
                show-search-result
                :search-result="searchResult"
                :area-columns-placeholder="['请选择', '请选择', '请选择']"
                @save="onSave"
                @delete="onDelete"
            />
        </div>
    </div>
</template>
<script>
import NavBar from 'components/common/navbar/NavBar'
import {reactive,toRefs,onMounted,computed} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import {Toast} from 'vant'
import {addAddress,EditAddress,DeleteAddress,getAddressDetail,getAddressList} from 'network/address'
import {tdist} from 'utils/address'
export default {
    name: 'AddressEdit',
    components:{
        NavBar
    },
    setup(){
        const route = useRoute()
        const router = useRouter()
        const state = reactive({
            // 区域列表
            areaList:{
                // 省
                province_list:{},
                // 市
                city_list:{},
                // 县
                county_list:{}
            },
            searchResult:[],
            addressInfo:{},

            type:'add',
            addressId:'',
            title:''
        })
        onMounted(()=>{
            // 省 市 区 县列表构造
            let _province_list = {};
            let _city_list = {};
            let _county_list = {};
            // console.log(tdist.getLev1());
            // forEach 遍历省
            tdist.getLev1().forEach(p=>{
                _province_list[p.id] = p.text;
                // forEach 遍历市
                tdist.getLev2(p.id).forEach(c=>{
                    // forEach 遍历县
                    _city_list[c.id] = c.text;
                    tdist.getLev3(c.id).forEach(q=>{
                        _county_list[q.id] = q.text;
                    })
                })
            })
            state.areaList.province_list = _province_list;
            state.areaList.city_list = _city_list;
            state.areaList.county_list = _county_list;

            // 获取是编辑还是添加页面
            // 接收参数
            console.log(route.query);
            const {type,addressId} = route.query;
            state.type = type;
            state.addressId = addressId;
            // 区域码

            // 状态为编辑的时候
            if(type == 'edit'){
                // 把订单的详情传过去
                getAddressDetail(addressId).then(res=>{
                    console.log(res);
                    const addressDetail = res;
                    let _areaCode = '';
                    // 拿到省份
                    const province = tdist.getLev1();
                    Object.entries(state.areaList.county_list).forEach(([id,text]) => {
                        // 找出当前对应的区
                        if(text == addressDetail.county){
                            // 找到区对应的几个省份
                            const provinceIndex = province.findIndex(item => item.id.substr(0,2) == id.substr(0,2));
                            const cityItem = Object.entries(state.areaList.city_list).filter(([cityId,city]) => cityId.substr(0,4) == id.substr(0,4));
                            console.log(cityItem[0][1])
                            if(province[provinceIndex].text == addressDetail.province && cityItem[0][1] == addressDetail.city){
                                _areaCode = id
                            }
                        }
                    })

                    state.addressInfo = {
                        name:addressDetail.name,
                        tel:addressDetail.phone,
                        province:addressDetail.province,
                        city:addressDetail.city,
                        county:addressDetail.county,
                        // 区域码
                        areaCode : _areaCode,
                        addressDetail:addressDetail.address,
                        isDefault:!!addressDetail.is_default
                    }
                })
            }

        })
        // 计算属性
        const title = computed(()=>{
            return state.type == 'add' ? '新增地址' : '编辑地址';
        })


        // 添加数据
        const onSave = (content) =>{
            // 把数据添加到每一个数据中
            const params = {
                name:content.name,
                phone:content.tel,
                province:content.province,
                address:content.addressDetail,
                city:content.city,
                county:content.county,
                is_default:content.isDefault ? 1 : 0
            }

            if(state.type == 'edit'){
                // 修改数据
                EditAddress(state.addressId,params);
            }else if(state.type == 'add'){
                // 调用接口，添加数据
                addAddress(params);
            } 
            Toast('保存成功！');
                setTimeout(()=>{
                router.back();
            },1000)
        }
        // 删除事件
        const onDelete = ()=>{
            DeleteAddress(state.addressId).then(res=>{
                Toast('删除成功！');
                setTimeout(()=>{
                    router.back();
                },1000)
            })
        }
        return{
            onDelete,
            onSave,
            ...toRefs(state),
            title
        }
    }
}
</script>
<style scoped>
    .a{
        margin-top: 60px;
    }
</style>
